# -*- coding: utf-8 -*-
import os
import shutil,re
from os.path import walk
# 还存在拼接路径时,一个是unicode,一个是str,导致拼接错误,31行
joinPath = os.path.join
isFile = os.path.isfile
isFolder = os.path.isdir
PathA = r"G:\PathA客户环境\康桥地产_352SP4\01升级后"
PathB = r"G:\PathB"
# PathA = r"%s" %raw_input("请客户环境目录: ")
# PathB = r"%s" %raw_input("请输入更新包目录: ")
# PathA = PathA.replace("\\","\\\\")+"\\\\"
# PathB = PathB.replace("\\","\\\\")+"\\\\"
copy_to_path = {"ERP":unicode(os.path.join(PathA,"ERP"),"utf8"),
                "WF":unicode(os.path.join(PathA,"WF"),"utf8"),
                "CZERP":unicode(os.path.join(PathA,"CZERP"),"utf8")
                }
def check_contain_chinese(check_str):
    for ch in check_str.decode('gb2312'):
        if u'\u4e00' <= ch <= u'\u9fff':
            return True
    return False

def copy_action(arg, dirname, filenames,):
    # 读取中文路径时，需要将gb2312的路径解码为unicode
    print u"准备拷贝%s目录下的文件..."%unicode(dirname,"gb2312")
    # 将完整路径截取PathB之后的后半部分
    diretory = dirname.replace(from_path, "")
    # 连接PathA和PathB的后半部分形成新的copy_to路径
    dirnameA = joinPath(to_path, unicode(diretory,"utf8"))
    # 检查dirnameA是否存在
    if isFolder(dirnameA):
        for FILE in filenames:
            copy_from = joinPath(dirname, FILE)
            copy_to = joinPath(dirnameA, FILE)
            if isFile(copy_from) and not isFile(copy_to):
                # 如果copy_from存在文件,且copy_to不存在文件,则从PathB->PathA
                shutil.copy2(copy_from,copy_to)
            elif isFile(copy_from) and isFile(copy_to):
                # 如果copy_from存在文件,且copy_to也存在文件,先删除copy_to,再从PathB->PathA(即覆盖copy_to的文件)
                os.remove(copy_to)
                shutil.copy2(copy_from, copy_to)
            elif isFolder(copy_from) and not isFolder(copy_to):
                # 如果不存在目录,则创建目录到PathA，创建中文路径的目录，需要编码为gb2312
                os.system("mkdir %s" % (copy_to.encode("gb2312")))
    else:
        # 如果没有相同的目录,则创建目录到pathA
        print "创建目录..."
        os.system("mkdir %s" %(dirnameA))
        for FILE in filenames:
            shutil.copy2(joinPath(dirname,FILE),joinPath(dirnameA, FILE))
    print u"%s目录下的文件拷贝完成!\n------------------------------------------------------"%unicode(dirname,"gb2312")

# 获取测试环境ERP文件夹内的工作流版本,确认是重构还是核心环境
def get_test_environment_version():
    erp_path = copy_to_path["ERP"]
    environment = {}
    with open(joinPath(erp_path,"MysoftVersion_WF.config"),"rb") as f:
        content = f.read().replace("\r\n","")
        # print content
        # 读版本文件,匹配文件内的版本号
        version = re.search("<Version>(.*)</Version>", content).group(1)
        erp_type = re.search("<ProductKey>(.*)</ProductKey>", content).group(1)
        # print version
        environment["version"]= version
        environment["erp_type"] = erp_type
    return environment

# 检查更新包下是否有SQL需要手动执行
def check_sql_exists():
    """
    检查更新包下是否有SQL需要手动执行
    :return:
    """
    PathB_Dir = os.listdir(PathB)
    for version_Folder in PathB_Dir:
        version_Folder = joinPath(PathB,version_Folder)
        # 只检查文件夹,更新说明.txt就排除不做检查
        if isFolder(version_Folder):
            sql_path = os.path.join(version_Folder,"sql")
            if "sql" in str(os.listdir(sql_path)):
                # sql_path = sql_path.encode("gb2312")
                sql_path = unicode(sql_path,"gb2312")
                print u"%s 路径下存在sql更新,需要手动执行sql" %sql_path
    print "---------------------------------------------------------"

if __name__ == "__main__":
    environment =  get_test_environment_version()
    # 如果版本号里面有CG标志,说明是重构环境,否则是核心环境
    if "cg" in environment["erp_type"]:
        # version = version.split("CG")[0]
        print "当前ERP的工作流版本: %s,是重构工作流!" %environment["version"]
        # PathB = raw_input("当前ERP的工作流版本: %s 重构工作流, 请输入更新包路径 :\n" %version)
        check_sql_exists()
        for files in os.listdir(PathB):
            #比如20180717的更新包下的文件夹不包含中文,且不是文件
            if not check_contain_chinese(files) and not os.path.isfile(files):
                # 最终拷贝文件是1.1807.2800下的"src"下的内容
                from_path = joinPath(os.path.join(PathB,files),"src")
                to_path = copy_to_path["WF"]
                walk(from_path,copy_action,to_path)
            #比如20180717的更新包下的文件夹名称包含"重构",且不是文件
            elif "重构" in files.decode("gb2312").encode("utf-8") and not os.path.isfile(files):
                from_path = joinPath(os.path.join(PathB, files),"src")
                to_path = copy_to_path["ERP"]
                walk(from_path, copy_action, to_path)
                # 获取ERP的上级目录下的所有文件名,用来判断是否有采招ERP,如果有采招ERP,就把重构ERP的文件拷贝到采招ERP下
                if "CZ" in str(os.listdir(os.path.join(to_path, ".."))):
                    to_path = copy_to_path["CZERP"]
                    walk(from_path, copy_action, to_path)

    else:
        print "当前ERP的工作流版本: %s,是核心工作流!" %environment["version"]
        # PathB = raw_input("当前ERP的工作流版本: %s 核心工作流, 请输入更新包路径" % version)
        check_sql_exists()
        for files in os.listdir(PathB):
            # print files.decode("gb2312")
            #比如20180717的更新包下的文件夹不包含中文,且不是文件
            if not check_contain_chinese(files) and not os.path.isfile(files):
                from_path = joinPath(os.path.join(PathB, files), "src")
                to_path = copy_to_path["WF"]
                walk(from_path,copy_action,to_path)
            #比如20180717的更新包下的文件夹名称包含"核心",且不是文件
            elif "核心" in files.decode("gb2312").encode("utf-8") and not os.path.isfile(files):
                from_path = joinPath(os.path.join(PathB, files), "src")
                to_path = copy_to_path["ERP"]
                walk(from_path, copy_action, to_path)
                # 获取ERP的上级目录下的所有文件名,用来判断是否有采招ERP,如果有采招ERP,就把核心ERP的文件拷贝到采招ERP下
                if "CZ" in str(os.listdir(os.path.join(to_path, ".."))):
                    to_path = copy_to_path["CZERP"]
                    walk(from_path, copy_action, to_path)